#include "MyServer.h"
#include <cstdio>
#include <cmath>
#include <windows.h>

void *MyServer::WorkingThread(void *v)
{
    MyServer *p = (MyServer *)v;

    for(int k=0;k<10;k++)
    {
        p->Log("Tick");
        Sleep(100);
    }
    p->Log("End Tick");
    pthread_exit(NULL);
    return 0;
}

MyServer::MyServer():mPort(0)
{
    pthread_mutex_init(&mMutex, NULL);
}

MyServer::~MyServer()
{
    pthread_mutex_destroy(&mMutex);
}

void MyServer::JoinThreads()
{
    int rc = pthread_join(mThread, NULL);
    if (rc)
    {
        Log("Join thread fail!\n");
    }
}

void MyServer::ListenToPort(const unsigned int &port)
{
    mPort=port;
    mRunning=true;

    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    int rc = pthread_create(&mThread, &attr, WorkingThread, (void *)this);
    if (rc)
    {
        Log("Create thread fail!\n");
    }

    pthread_attr_destroy(&attr);
    Log("End..\n");
}

bool MyServer::IsRunning()
{
    return mRunning;
}

void MyServer::Stop()
{
    //JoinThreads();
    Log("Stop...\n");
    mRunning=false;
}

void MyServer::Log(std::string str)
{
    pthread_mutex_lock (&mMutex);
    printf("%s\n",str.c_str());
    pthread_mutex_unlock (&mMutex);
}
